<template>
  <view class="template-activity">
    <view class="container">
      <view class="nav_title">
        <text class="title-text">电商平台</text>

        <!-- 电商平台菜单 -->
        <view class="platform-menu">
          <view 
            v-for="platform in platforms" 
            :key="platform.value"
            class="platform-item" 
            @click="tn(platform.value)"
          >
            <view :class="['platform-icon', getPlatformIconClass(platform.value)]">
              <view :class="{
                'tn-icon-shop': platform.value === 'PIN_DUO_DUO',
                'tn-icon-cart': platform.value === 'TAO_BAO',
                'tn-icon-video': platform.value === 'DOU_YIN'
              }"></view>
            </view>
            <text class="platform-text">{{ platform.label }}</text>
          </view>
        </view>

        <!-- 平台输入控件 -->
        <view class="platform-controls" v-if="showControls">
          <!-- 拼多多输入框 -->
          <input
            v-if="activeControl === 'PIN_DUO_DUO'"
            class="pdd-input"
            v-model="pddInput"
            @input="handlePddInputChange"
            placeholder="请输入商品链接"
          />

          <!-- 商品信息预览 -->
          <view v-if="activeControl === 'PIN_DUO_DUO' && goodsInfo" class="goods-preview">
            <image 
              :src="goodsInfo.goods_thumbnail_url" 
              mode="aspectFit" 
              class="goods-image"
            />
            <view class="goods-info">
              <text class="goods-title">{{ goodsInfo.goods_name }}</text>
              <text class="goods-price">¥{{ goodsInfo.min_group_price / 100 }}</text>
              <text class="goods-sales">{{ goodsInfo.sales_tip }}</text>
            </view>
          </view>

          <!-- 淘宝和抖音图片上传 -->
          <view
            v-if="activeControl === 'TAO_BAO' || activeControl === 'DOU_YIN'"
            class="upload-control"
            @click="chooseImage"
          >
            <view class="upload-content" v-if="!tempFilePath">
              <text class="upload-icon tn-icon-upload"></text>
              <text class="upload-text">点击上传图片</text>
              <text class="upload-desc">支持jpg、png格式</text>
            </view>
            <image
              v-else
              :src="tempFilePath"
              mode="aspectFit"
              class="preview-image"
            ></image>
          </view>

          <!-- 分享按钮 -->
          <button class="share-button" @click="handleShare">
            <text class="share-icon tn-icon-share"></text>
            <text>分享商品</text>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "Discovery",
  data() {
    return {
      showControls: false,
      activeControl: "",
      pddInput: "",
      tempFilePath: "", // 临时图片路径
      uploadedImageUrl: "", // 上传后的图片URL
      goodsInfo: null, // 商品信息
      platforms: [], // 平台数据
    };
  },

  methods: {
    // 获取平台字典数据
    async getPlatformDict() {
      try {
        const response = await this.$minApi.getDict({
          dictCode: 'GOU_WU_PING_TAI',
          status: true,
          pageSize: 100,
        });

        if (response.success && response.data?.list) {
          this.platforms = response.data.list.sort((a, b) => a.sort - b.sort);
        }
      } catch (error) {
        console.error('获取平台字典数据失败:', error);
      }
    },

    // 获取平台图标类名
    getPlatformIconClass(value) {
      const classMap = {
        'PIN_DUO_DUO': 'pdd-color',
        'TAO_BAO': 'taobao-color',
        'DOU_YIN': 'douyin-color'
      };
      return classMap[value] || '';
    },

    // 跳转
    tn(platformValue) {
      this.activeControl = platformValue;
      this.showControls = true;
      this.tempFilePath = ""; // 重置图片
      this.uploadedImageUrl = ""; // 重置上传的图片URL
      this.pddInput = ""; // 重置输入
      this.goodsInfo = null; // 重置商品信息
    },

    // 上传图片到服务器
    async uploadImage(tempFilePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: this.$minApi.imgOrigin + '/api/upload/single',
          filePath: tempFilePath,
          name: 'file',
          formData: {
            folder: 'products/share'
          },
          success: (uploadRes) => {
            try {
              const result = JSON.parse(uploadRes.data);
              if (result.success && result.data?.url) {
                this.uploadedImageUrl = result.data.url;
                resolve(result.data.url);
              } else {
                reject(new Error('上传失败'));
              }
            } catch (error) {
              reject(error);
            }
          },
          fail: (error) => {
            reject(error);
          }
        });
      });
    },

    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          try {
            this.tempFilePath = res.tempFilePaths[0];
            await this.uploadImage(this.tempFilePath);
          } catch (error) {
            console.error('Upload failed:', error);
            uni.showToast({
              title: '图片上传失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },

    // 解析拼多多口令
    async parsePddCommand(command) {
      try {
        // 调用后端API解析口令
        const res = await this.$minApi.parsePddCommand({
          command: command
        });
        
        if (res.success && res.data) {
          this.goodsInfo = res.data;
          // 如果解析成功，自动设置商品图片
          if (this.goodsInfo.goods_thumbnail_url) {
            this.uploadedImageUrl = this.goodsInfo.goods_thumbnail_url;
          }
          // 显示商品信息提示
          uni.showToast({
            title: '商品信息获取成功',
            icon: 'success'
          });
        } else {
          throw new Error('口令解析失败');
        }
      } catch (error) {
        console.error('解析口令失败:', error);
        uni.showToast({
          title: '口令解析失败',
          icon: 'none'
        });
      }
    },

    // 处理拼多多输入变化
    async handlePddInputChange(value) {
      if (value && value.includes('复制')) {
        // 延迟执行以等待输入完成
        setTimeout(() => {
          this.parsePddCommand(this.pddInput);
        }, 500);
      }
    },

    // 处理分享
    async handleShare() {
      if (this.activeControl === "PIN_DUO_DUO" && !this.pddInput) {
        uni.showToast({
          title: "请输入商品链接",
          icon: "none",
        });
        return;
      }
      if (
        (this.activeControl === "TAO_BAO" || this.activeControl === "DOU_YIN") &&
        !this.uploadedImageUrl
      ) {
        uni.showToast({
          title: "请上传商品图片",
          icon: "none",
        });
        return;
      }

      try {
        const shareData = {
          platform: this.activeControl, // 购物平台
          command: this.pddInput, // 口令
          imagePath: this.uploadedImageUrl, // 图片路径
          shareTime: new Date().toISOString(), // 分享发起时间
          status: 0, // 状态：0已结束 1进行中
        };

        // 如果是拼多多平台且有商品信息，添加额外信息
        if (this.activeControl === 'PIN_DUO_DUO' && this.goodsInfo) {
          shareData.goodsInfo = {
            title: this.goodsInfo.goods_name,
            price: this.goodsInfo.min_group_price / 100,
            thumbnail: this.goodsInfo.goods_thumbnail_url,
            sales: this.goodsInfo.sales_tip,
          };
        }

        const res = await this.$minApi.createPintuan(shareData);
        if (res.success) {
          uni.showToast({
            title: "分享成功",
            icon: "success",
          });
          // 重置表单
          this.pddInput = "";
          this.tempFilePath = "";
          this.uploadedImageUrl = "";
          this.showControls = false;
        } else {
          throw new Error("分享失败");
        }
      } catch (error) {
        uni.showToast({
          title: "分享失败",
          icon: "none",
        });
      }
    },
  },
  created() {
    this.getPlatformDict();
  },
};
</script>

<style lang="scss" scoped>
.template-activity {
  min-height: 100vh;
  background: #f5f7fa;
}

.container {
  width: 100%;
  padding: 30rpx;
  box-sizing: border-box;
}

/* 标题 */
.nav_title {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 40rpx 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;

  .title-text {
    font-size: 36rpx;
    font-weight: 600;
    color: #1a73e8;
    margin-bottom: 40rpx;
    text-align: center;
    display: block;
  }
}

/* 电商平台菜单 */
.platform-menu {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin: 20rpx auto 40rpx;
  padding: 0 40rpx;
  box-sizing: border-box;
  max-width: 600rpx;

  .platform-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-6rpx);
    }

    .platform-icon {
      width: 100rpx;
      height: 100rpx;
      border-radius: 20rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 16rpx;
      font-size: 46rpx;
      color: #ffffff;
      box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;

      &.pdd-color {
        background: linear-gradient(135deg, #1a73e8, #4285f4);
      }

      &.taobao-color {
        background: linear-gradient(135deg, #ff6b22, #ff9466);
      }

      &.douyin-color {
        background: linear-gradient(135deg, #fe2c55, #ff6b88);
      }
    }

    .platform-text {
      font-size: 28rpx;
      color: #333333;
      font-weight: 500;
    }
  }
}

/* 平台控件样式 */
.platform-controls {
  width: 100%;
  padding: 0 40rpx;
  box-sizing: border-box;
  max-width: 800rpx;
  margin: 0 auto;

  .pdd-input {
    width: 100%;
    height: 88rpx;
    border: 2rpx solid #e8eaed;
    border-radius: 12rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
    color: #333333;
    background: #ffffff;
    transition: all 0.3s ease;
    box-sizing: border-box;

    &:focus {
      border-color: #1a73e8;
      box-shadow: 0 0 0 2rpx rgba(26, 115, 232, 0.1);
    }

    &::placeholder {
      color: #9aa0a6;
    }
  }

  .upload-control {
    position: relative;
    width: 100%;
    height: 200rpx;
    border: 2rpx dashed #e8eaed;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #ffffff;
    transition: all 0.3s ease;
    box-sizing: border-box;
    cursor: pointer;

    &:hover {
      border-color: #1a73e8;
      background: rgba(26, 115, 232, 0.02);
    }

    .upload-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #5f6368;

      .upload-icon {
        font-size: 50rpx;
        color: #1a73e8;
        margin-bottom: 16rpx;
      }

      .upload-text {
        font-size: 28rpx;
        font-weight: 500;
        margin-bottom: 8rpx;
      }

      .upload-desc {
        font-size: 24rpx;
        color: #9aa0a6;
      }
    }

    .preview-image {
      width: 100%;
      height: 100%;
      border-radius: 12rpx;
      object-fit: contain;
    }
  }

  /* 分享按钮样式 */
  .share-button {
    width: 100%;
    height: 88rpx;
    margin-top: 40rpx;
    border: none;
    border-radius: 12rpx;
    background: linear-gradient(135deg, #1a73e8, #4285f4);
    color: #ffffff;
    font-size: 32rpx;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    box-shadow: 0 8rpx 16rpx rgba(26, 115, 232, 0.2);
    padding: 0;

    &::after {
      border: none;
    }

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 4rpx 8rpx rgba(26, 115, 232, 0.2);
    }

    .share-icon {
      font-size: 36rpx;
      margin-right: 12rpx;
    }
  }
}

/* 商品预览样式 */
.goods-preview {
  margin-top: 30rpx;
  background: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  display: flex;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  .goods-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
  }

  .goods-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .goods-title {
      font-size: 28rpx;
      color: #333333;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .goods-price {
      font-size: 32rpx;
      color: #ff4d4f;
      font-weight: bold;
    }

    .goods-sales {
      font-size: 24rpx;
      color: #999999;
    }
  }
}
</style>


